/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package timers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;

import main.Bot;
import main.CommonMethods;
import main.UserCentral;

import org.apache.log4j.Logger;

import database.DBConnectionFactory;

/**
 * A timer for alarms
 * 
 * 
 */
public class AlarmTimer extends Timer {
   /**
    * A Class that represents a task to be done when the timer runs out
    * 
    * 
    */
   private static class ToDoTask extends TimerTask {
	  private final String user;
	  private final String message;

	  public ToDoTask(final String user, final String message) {
		 super();
		 this.user = user;
		 this.message = message;
	  }

	  @Override
	  public void run() {
		 Connection con = DBConnectionFactory.getConnectionHandler().getConnection();
		 PreparedStatement ps = null;
		 try {
			ps = con.prepareStatement("DELETE FROM alarm WHERE " + "mainnick = ?");
			ps.setString(1, user);
			ps.executeUpdate();

			Bot.getInstance().getTimerHandler().removeAlarmTimer(user);
		 } catch (final SQLException e) {
			Logger.getLogger("Error").error("", e);
		 } finally {
			try {
			   ps.close();
			} catch (final Exception e) {
			   Logger.getLogger("Error").error("", e);
			}
		 }
		 for (final String s : UserCentral.getInstance().getCurrentNicks(user)) {
			Bot.getInstance().sendMessage(s, (user + ": " + ("".equals(message) ? "Your alarm just went off!" : message)));
		 }
		 CommonMethods.doSMSNotification(user, 2, "");
	  }
   }

   private final String user;

   public AlarmTimer(final String user, final Long delay, final String message) {
	  super();
	  this.user = user;
	  this.schedule(new ToDoTask(user, message), delay);
   }

   public String getUser() {
	  return user;
   }
}
